package org.i9.slb.platform.anseko.provider.task.pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.stereotype.Component;

/**
 * 命令执行异步线程池
 *
 * @author R12
 * @date 2018.08.30
 */
@Component
public class CommandExecuteSchedulerPool {

    private final ThreadPoolExecutor executor = new ThreadPoolExecutor(50, 500, Integer.MAX_VALUE, TimeUnit.DAYS,
            new ArrayBlockingQueue<Runnable>(30000, false),
            new ThreadFactory() {
                final ThreadGroup group = Thread.currentThread().getThreadGroup();
                final AtomicInteger threadNumber = new AtomicInteger(1);
                final String namePrefix = "command-pool";

                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
                    if (t.isDaemon()) {
                        t.setDaemon(false);
                    }
                    if (t.getPriority() != Thread.NORM_PRIORITY) {
                        t.setPriority(Thread.NORM_PRIORITY);
                    }
                    return t;
                }
            }
    );

    public <T> Future<T> submit(Callable<T> task) {
        return this.executor.submit(task);
    }
}
